﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace MemoryTest
{
    class TestClassHasEvent
    {
        public delegate void TestEventHandler(object sender, EventArgs e);
        public event TestEventHandler YourEvent;
        protected void OnYourEvent(EventArgs e)
        {
            if (YourEvent != null) YourEvent(this, e);
        }
    }
    class TestListener:IDisposable
    {
        byte[] m_ExtraMemory = new byte[1000000];

        private TestClassHasEvent _inject;
        public TestListener(TestClassHasEvent inject)
        {
            _inject = inject;
            _inject.YourEvent += new TestClassHasEvent.TestEventHandler(_inject_YourEvent);
            //take care
            SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);
        }

        void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        void _inject_YourEvent(object sender, EventArgs e)
        {

        }

        void IDisposable.Dispose()
        {
            SystemEvents.DisplaySettingsChanged -= new EventHandler(SystemEvents_DisplaySettingsChanged);
        }
    }

    class TestListener2
    {
        byte[] m_ExtraMemory = new byte[1000000];

        private TestClassHasEvent _inject;
        public TestListener2(TestClassHasEvent inject)
        {
            _inject = inject;
            _inject.YourEvent += new TestClassHasEvent.TestEventHandler(_inject_YourEvent);
        }

        void _inject_YourEvent(object sender, EventArgs e)
        {

        }
    }

    class Program
    {
        static void DisplayMemory()
        {
            Console.WriteLine("Total memory: {0:###,###,###,##0} bytes", GC.GetTotalMemory(true));
        }
        static void Main()
        {
            DisplayMemory();
            Console.WriteLine();
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("--- New Listener #{0} ---", i + 1);
                //take care ,memory leak
                //var listener = new TestListener(new TestClassHasEvent());

                using (var listener = new TestListener(new TestClassHasEvent()))
                {

                }
                ////listener = null; //可有可无  

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                DisplayMemory();

            }
            Console.Read();
        }
    }
}
